import { createSlice } from "@reduxjs/toolkit";
import request from "@/utils/axios";
import { getToken, setToken } from "@/utils/token";

const user = createSlice({
  //模块名
  name: "user",
  // 数据状态
  initialState: {
    //持久化
    tooken: getToken() || "",
    isLogin: false,
    userInfo:{}
  },
  // 同步修改数据的方法
  reducers: {
    setTooken(state, action) {
      state.tooken = action.payload;
    }, 
    setIsLogin(state, action) {
      state.isLogin = action.payload;
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearAll(state,action){
      state.tooken = "";
      state.isLogin = false;
      state.userInfo = {};
      localStorage.clear();
    }
}
})

 const { setTooken, setIsLogin,setUserInfo,clearAll } = user.actions;

//异步方法来完成登录
const fechLogin = (params) => {

  return async (dispatch) => {
    // 1. 发送请求
  const res = await  request.post("authorizations",params)
    // 2. 修改状态
    setToken(res.data.token);
    dispatch(setTooken(res.data.token));
    if(res.message == "OK"){
      dispatch(setIsLogin(true))
    } else{
      dispatch(setIsLogin(false))
    }
    return res.message
  }
}

//获取个人信息
const fechUserInfo = () => {

  return async (dispatch) => {
    // 1. 发送请求
  const res = await  request.get("user/profile")
    // 2. 修改状态
    dispatch(setUserInfo(res.data));
    return res
  }
}

export { setTooken, fechLogin,setUserInfo,fechUserInfo,clearAll };

export default user.reducer;